package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.GoodClassDao;
import entity.GoodsClass;
import net.sf.json.JSONArray;
import service.GoodsClassService;

@WebServlet("*.class")
public class GoodsClassServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	GoodsClassService gcService = new GoodsClassService();
	
    public GoodsClassServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		int index = uri.lastIndexOf("/");
		String action = uri.substring(index+1);
		switch(action) {
		case "one.class":
			getGoodsOneClass(request,response);
			break;
		case "two.class":
			getGoodsTwoClass(request,response);
			break;
		case "oneToTwo.class":
			getGoodsOneClassToTwo(request,response);
			break;
		default:
			break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	//获取一级商品分类1
	protected void getGoodsOneClass(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<GoodsClass> goodsOneClass = gcService.getGoodsOneClass();
		request.setAttribute("goodsOneClass", goodsOneClass);
		request.getRequestDispatcher("shop/goodAdd.jsp").forward(request, response);
	}
	//获取一级商品分类2
	protected void getGoodsOneClassToTwo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<GoodsClass> goodsOneClass = gcService.getGoodsOneClass();
		request.setAttribute("goodsOneClass", goodsOneClass);
		request.getRequestDispatcher("shop/goodImgMulti.jsp").forward(request, response);
	}
	//获取二级商品分类
	protected void getGoodsTwoClass(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int oneClassId = Integer.parseInt(request.getParameter("oneClassId"));
		List<GoodsClass> goodsTwoClass = gcService.getGoodsTwoClass(oneClassId);
		//将json所需的包放到lib里面,将list转换为json
		JSONArray json=JSONArray.fromObject(goodsTwoClass);
		//响应前台页面
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/json");
		PrintWriter out=response.getWriter();
		out.println(json);//打印json，为了前台页面获取
		out.flush();//刷新流
		out.close();//关闭流
	}

}
